#include "MCDrawLinearDimensionCommand.h"
#include <MCIncidentConstraint.h>
#include <iostream>

MCDrawLinearDimensionCommand::MCDrawLinearDimensionCommand(MCCommandManager *owner) :
    MCCommand(owner),
    _currentStage(MCDrawLinearDimensionStage::DM_SetStartPoint)
{
    _dimensionVisual = new MCLinearDimensionsVisual(presenter, MCLinearDimension2D());
    presenter->addVisualItem(_dimensionVisual);
}

MCDrawLinearDimensionCommand::~MCDrawLinearDimensionCommand()
{
}

void MCDrawLinearDimensionCommand::onMouseDown(IMouseArgs &args)
{
    if (args.isLeftMousePressed())
    {
        if (_currentStage == MCDrawLinearDimensionStage::DM_SetStartPoint)
        {
            _settedStartPoint = args.globalPos();
            _dimensionVisual->update(_settedStartPoint, _settedStartPoint);

            if (presenter->gripAt(args.position()) != nullptr)
            {
                MCIncidentContraint *c = new MCIncidentContraint(presenter->gripAt(args.position()), _dimensionVisual->grips()[0]);
                presenter->constraintManager()->addConstraint(c);
            }

            _currentStage = MCDrawLinearDimensionStage::DM_SetEndPoint;
        }
        else if (_currentStage == MCDrawLinearDimensionStage::DM_SetEndPoint)
        {
            _settedEndPoint = args.globalPos();
            _dimensionVisual->update(_settedStartPoint, _settedEndPoint);

            if (presenter->gripAt(args.position()) != nullptr)
            {
                MCIncidentContraint *c2 = new MCIncidentContraint(presenter->gripAt(args.position()), _dimensionVisual->grips()[1]);
                presenter->constraintManager()->addConstraint(c2);
            }

            _currentStage = DM_SetHeight;
        }
        else if (_currentStage == MCDrawLinearDimensionStage::DM_SetHeight)
        {
            double height = args.globalPos().distanceTo(_dimensionVisual->linearDimension().dimensionLineNoTransform().midPoint());
            _dimensionVisual->update(_settedStartPoint, _settedEndPoint, height);
            finalize();
        }
    }
    else if (args.isRightMousePressed())
    {
        terminate();
    }
}

void MCDrawLinearDimensionCommand::onMouseUp(IMouseArgs &args)
{
}

void MCDrawLinearDimensionCommand::onMouseMove(IMouseArgs &args)
{
    if (_currentStage == DM_SetEndPoint)
    {
        _settedEndPoint = args.globalPos();
        _dimensionVisual->update(_settedStartPoint, _settedEndPoint);
    }
    else if (_currentStage == DM_SetHeight)
    {
        double height = args.globalPos().distanceTo(_dimensionVisual->linearDimension().dimensionLineNoTransform().midPoint());
        _dimensionVisual->update(_settedStartPoint, _settedEndPoint, height);
    }
}

void MCDrawLinearDimensionCommand::terminate()
{
    presenter->removeVisualItem(_dimensionVisual);
}
